package com.ajmd.onlineexam.controller;

import com.ajmd.onlineexam.baseUtil.CommonResult;
import com.ajmd.onlineexam.baseUtil.FacePlusPlusUtils;
import com.ajmd.onlineexam.baseUtil.JWTUtils;
import com.ajmd.onlineexam.entity.StudentPO;
import com.ajmd.onlineexam.enumeration.AppExceptionCodeEnum;
import com.ajmd.onlineexam.enumeration.StaticFinalValue;
import com.ajmd.onlineexam.mapper.StudentMapper;
import com.ajmd.onlineexam.scheduledTask.ClearImg;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.unit.DataSize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author ajmd
 * @since 2023/3/14 14:59
 */

@Api("api接口")
@RestController
@RequestMapping("/api")
public class ApiController {
//    @Value("${number}")
//    private int number;

    // 图片保存的根路径（从 application.yml 中读取）
    @Value("${spring.servlet.multipart.location}")
    private String location;

    // 允许上传的最大文件大小（从 application.yml 中读取）
    @Value("${spring.servlet.multipart.max-file-size}")
    private String maxFileSize;

    @Resource
    private ClearImg clearImg;
    @Resource
    private StudentMapper studentMapper;
    @Resource
    private RedisTemplate redisTemplate;


    @ApiOperation("刷新token")
    @PostMapping("/refreshToken")
    public CommonResult refreshToken(@RequestParam String account){

        Map<String, String> map = new HashMap<>();
        map.put("account",account);
        String token = JWTUtils.getToken(map);
        return CommonResult.ok().data("token",token);
    }

    // 接收图片上传请求的接口
    @PostMapping(value = "/image")
    public CommonResult uploadImage(@RequestParam("file") MultipartFile file,
                                    @RequestParam(required = false) String path,
                                    HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 检查文件是否为空
        if (file.isEmpty()) {
            return CommonResult.error(AppExceptionCodeEnum.IMG_UPLOAD_ERROR)
                    .appendMessage("图片不存在！");
        }
        if(ObjectUtils.isEmpty(path)){
            path="avatar";
        }


        // 检查文件大小是否超过限制
        long maxSize = DataSize.parse(StaticFinalValue.UPLOAD_IMG_MAX_SIZE).toBytes();
        if (file.getSize() > maxSize) {
            return CommonResult.error(AppExceptionCodeEnum.IMG_UPLOAD_ERROR)
                    .appendMessage("文件大小不能超过" + FileUtils.byteCountToDisplaySize(maxSize));
        }

        // 获取文件扩展名
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isBlank(extension)) {
            extension = "jpg";
        }
        //完整路径拼接
        String rootPath = "/img/"+path;
        String imgPath = location + rootPath;
        // 生成文件名
        String filename = UUID.randomUUID()+ "." + extension;
        File destFile = new File(imgPath, filename);
        // 保存上传的文件
        file.transferTo(destFile);
        // 返回文件 URL
        String fileUrl = rootPath + "/" + filename;
        return CommonResult.ok().message("文件上传成功").data("fileUrl",fileUrl);
    }

    @DeleteMapping(value="/image")
    public CommonResult deleteImage(@RequestParam("imgPath") String imgPath){
        String path = location + imgPath;
        // 创建要删除的文件对象
        File file = new File(path);
        // 如果文件不存在，则直接返回
        if (!file.exists()) {
            return CommonResult.error(AppExceptionCodeEnum.IMG_DELETE_ERROR).appendMessage("图片不存在");
        }
        boolean delete = file.delete();
        return CommonResult.ok("图片删除成功！");
    }

    @DeleteMapping("/clearImage")
    public CommonResult clearImage(){

        clearImg.handleClearImage();
        return CommonResult.ok().message("已通知执行上传图片清理");
    }


    @PostMapping("/facialVerification")
    public CommonResult facialVerification(@RequestParam String account,
                                           @RequestParam MultipartFile file) throws IOException {
        //查询用户照片
        StudentPO studentPO = studentMapper.selectById(account);
        if(ObjectUtils.isEmpty(studentPO.getUserImg())){
            return CommonResult.error().message("请先完善个人信息，上传本人正面照");
        }
        String userImgPath = location+studentPO.getUserImg();

        byte[] bytes = file.getBytes(); // 读取文件的字节数组
        String fileBase64 = new String(Base64.getEncoder().encode(bytes)); // 对字节数组进行 Base64 编码
        float similar = FacePlusPlusUtils.faceCompare(fileBase64, userImgPath);
        return CommonResult.ok().data("similar",similar);
    }

//    @GetMapping("/redis/get")
//    private CommonResult getRedis(@RequestParam("key") String key){
//        return CommonResult.ok().data("data",redisTemplate.opsForValue().get(key));
//    }
//
//    @PutMapping("/redis/set")
//    private CommonResult setRedis(@RequestParam("key") String key,@RequestParam("value") String value){
//        redisTemplate.opsForValue().set(key,value);
//        return CommonResult.ok();
//    }

}
